package com.tkjt.pms.server.core;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.tkjt.pms.server.IndexServer;
import com.tkjt.pms.server.ServerService;
import com.tkjt.pms.server.common.InnerServerTask;
import com.tkjt.pms.server.common.ServerParam;
import com.tkjt.pms.server.common.ServerTask;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class IndexServerImpl implements IndexServer {

	private ExecutorService parallelExecutorService = Executors.newFixedThreadPool(16);

	private ExecutorService singleExecutorService = Executors.newFixedThreadPool(1);

	@Autowired
	private Map<String, ServerService> serverServiceRepositories = new HashMap<String, ServerService>();

	@Override
	public void doIndexServer(List<ServerTask> serverTasks) {

		log.info("run index report server....");

		for (ServerTask task : serverTasks) {
			InnerServerTask innerServerTask = new InnerServerTask(task.getServerParam());
			ServerService serverService = serverServiceRepositories.get(innerServerTask.getServerServiceName());
			innerServerTask.setServerService(serverService);
			String serverType = innerServerTask.getServerType();
			if (!StringUtils.isEmpty(serverType) && ServerParam.SERVER_TYPE_SINGLE.equals(serverType)) {
				singleExecutorService.submit(innerServerTask);
			} else {
				parallelExecutorService.submit(innerServerTask);
			}
		}

	}

	@Override
	public boolean isFinishExecutor(String serverType) {
		ThreadPoolExecutor threadPoolExecutor = null;
		if (ServerParam.SERVER_TYPE_SINGLE.equals(serverType)) {
			threadPoolExecutor = (ThreadPoolExecutor) singleExecutorService;
		} else {
			threadPoolExecutor = (ThreadPoolExecutor) parallelExecutorService;
		}
		long taskCount = threadPoolExecutor.getQueue().size();
		int activeCount = threadPoolExecutor.getActiveCount();
		if (taskCount > 0 || activeCount > 0) {
			return false;
		}
		return true;
	}

	@Override
	public void shutdownAllTasks(String serverType) {
		ThreadPoolExecutor threadPoolExecutor = null;
		if (ServerParam.SERVER_TYPE_SINGLE.equals(serverType)) {
			threadPoolExecutor = (ThreadPoolExecutor) singleExecutorService;
		} else {
			threadPoolExecutor = (ThreadPoolExecutor) parallelExecutorService;
		}
		try {
			threadPoolExecutor.shutdownNow();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}
}
